package booksystem.controller;

import booksystem.dao.CartDao;
import booksystem.dao.UserDao;
import booksystem.dao.impl.CartDaoImpl;
import booksystem.dao.impl.UserDaoImpl;
import booksystem.entity.Cart;
import booksystem.entity.User;
import booksystem.utils.CommonUtils;
import booksystem.utils.MD5Utils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

@WebServlet(name = "UserServlet", urlPatterns = "/user")
public class UserServlet extends BaseServlet {
    private UserDao userDao = new UserDaoImpl();
    private CartDao cartDao = new CartDaoImpl();

    /*
     * 注册接口
     * */
    public void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, IllegalAccessException {
        Map<String, String[]> params = req.getParameterMap();
        User user = new User();
        // 处理用户填写的内容
        BeanUtils.populate(user, params);
        // 验证用户输入的验证码
        String vcode = req.getParameter("vcode");
        HttpSession session = req.getSession();
        // 判断发送的验证码与用户输入的验证码是否相同
        if (vcode.toUpperCase().equals(((String) session.getAttribute("vcode")).toUpperCase())) {
            // 使用MD5将密码加密存储到数据库
            String pwd = MD5Utils.md5(user.getPassword());
            user.setPassword(pwd);
            user.setId(CommonUtils.getUUID());
            int a = userDao.save(user);
            if (a == 1) {
                System.out.println("注册成功");
                resp.sendRedirect("/");
            } else {
                System.out.println("注册失败");
            }
        } else {
            System.out.println("验证码不正确");
            resp.sendRedirect("/");
        }
    }

    /*
     * 验证username是否可用
     * */
    public void validateUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    }

    /*
     * 登录
     * */
    public void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 获取参数
        String account = req.getParameter("account");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        // 2. 处理业务
        // 根据 account 和 password 到数据库查询
        boolean status = account.contains("@");
        String pwd = "";
        if (code == null) {
            pwd = password;
        } else {
            pwd = MD5Utils.md5(password);
        }
        User loginUser = null;
        if (status) {
            loginUser = userDao.emailLogin(account, pwd);
        } else {
            loginUser = userDao.phoneLogin(account, pwd);
        }
        // 3. 返回响应内容
        HttpSession session = req.getSession();
        String session_code = (String) session.getAttribute("code");
        // 3.1 如果登录成功，请求转发到main.jsp, 否则重定向到login.jsp
        if (loginUser != null && (code == session_code || code.toUpperCase().equals(session_code.toUpperCase()))) {
            // 如果选择了七天免登录，要给客户端添加cookie
            String freeLogin = req.getParameter("freeLogin");
            if ("7".equals(freeLogin)) {
                // 创建cookie对象
                Cookie userCookie = new Cookie("account", account);
                Cookie pwdCookie = new Cookie("password", pwd);
                userCookie.setMaxAge(60 * 60 * 24 * 7);
                pwdCookie.setMaxAge(60 * 60 * 24 * 7);
                // 将cookie对象添加到客户端
                resp.addCookie(userCookie);
                resp.addCookie(pwdCookie);
            }

            // 将username共享在session中，便于main.jsp显示用户信息
            // 会话属性
            session.setAttribute("user_id", loginUser.getId());
            session.setAttribute("username", loginUser.getUsername());
            session.setAttribute("email", loginUser.getEmail());
            session.setAttribute("phone", loginUser.getPhone());
            // 请求属性
            req.setAttribute("user_id", loginUser.getId());
            req.setAttribute("username", loginUser.getUsername());
            req.setAttribute("email", loginUser.getEmail());
            req.setAttribute("phone", loginUser.getPhone());
            // 请求转发共用一个请求对象
//            req.getRequestDispatcher("/main.jsp").forward(req, resp);
            //响应重定向，不能共用request对象，但共用session对象
            resp.sendRedirect("/");
        } else {
            resp.sendRedirect("/");
        }

    }

    /*
     * 注销
     * */
    public void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 用户退出登录，销毁session对象
        HttpSession session = req.getSession();
        session.removeAttribute("username");
        session.removeAttribute("email");
        session.removeAttribute("phone");
//        session.invalidate();
        // 删除cookie
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie : cookies) {
            cookie.setMaxAge(0);
            cookie.setPath("/");
            resp.addCookie(cookie);
        }
        resp.sendRedirect("/");
    }

    /*
     * 修改密码
     * */
    public void changePassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 获取参数
        HttpSession session = req.getSession();
        String email = (String) session.getAttribute("email");
//        String code = req.getParameter("code");
        String oldPassword = req.getParameter("oldPassword");
        String newPassword = req.getParameter("newPassword");
        // 2. 验证邮箱和旧密码是否填写正确
        String pwd = MD5Utils.md5(oldPassword);
        User loginUser = userDao.emailLogin(email, pwd);
        if (loginUser != null) {

            userDao.changePassword(email, pwd, MD5Utils.md5(newPassword));
            System.out.println("修改成功");

        } else {
            // 3.2 否则取消执行修改操作
            System.out.println("修改失败");
        }
        resp.sendRedirect("/");

    }

}


